package lambdasinaction.chap3;

import lombok.SneakyThrows;

import java.io.*;
import java.util.function.Function;

public class ExecuteAround {

    public static void main(String... args) throws IOException {

        // method we want to refactor to make more flexible
//        String result = processFileLimited();
//        System.out.println(result);
//
//        System.out.println("---");
//
//        String oneLine = processFile((BufferedReader b) -> b.readLine());
//        System.out.println(oneLine);
//
//        String twoLines = processFile((BufferedReader b) -> b.readLine() + b.readLine());
//        System.out.println(twoLines);

        //
		handle(
		        getBufferedReader("lambdasinaction/chap3/data.txt"),
                a -> a + a
                );


    }

	@SneakyThrows
    private static void handle(BufferedReader bufferedReader, Function<String, String> function) {
		String line = bufferedReader.readLine();
        System.out.println(function.apply(line));

    }

	public static String processFileLimited() throws IOException {
        try (BufferedReader br =
                     new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))) {
            return br.readLine();
        }
    }


    public static String processFile(BufferedReaderProcessor p) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))) {
            return p.process(br);
        }

    }

    public static BufferedReader getBufferedReader(String filePath) throws IOException {
        InputStream in = ClassLoader.getSystemResourceAsStream(filePath);
        return new BufferedReader(new InputStreamReader(in)) ;

    }

    @FunctionalInterface
    public interface BufferedReaderProcessor {
        String process(BufferedReader b) throws IOException;

    }
}
